package com.demo2do.fms.admin.web.controller.authority.user;

import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.entity.page.Page;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.resolver.Preloading;
import com.demo2do.fms.admin.service.authority.OrganizationService;
import com.demo2do.fms.admin.service.authority.ResourceService;
import com.demo2do.fms.admin.service.authority.RoleService;
import com.demo2do.fms.admin.service.authority.UserService;
import com.demo2do.fms.admin.service.supplier.SupplierService;
import com.demo2do.fms.admin.web.resolver.Secure;
import com.demo2do.fms.entity.authority.Organization;
import com.demo2do.fms.entity.authority.Resource;
import com.demo2do.fms.entity.authority.Role;
import com.demo2do.fms.entity.authority.RoleTemplate;
import com.demo2do.fms.entity.authority.User;
import com.demo2do.fms.entity.supplier.common.Supplier;

/**
 * 总部用户管理
 * 
 * @author Ysy
 *
 */
@Controller
@RequestMapping("/admin-users")
@MenuSetting("menu-authority")
public class AdminUserController {
	
	private static final Logger logger = LoggerFactory.getLogger(AdminUserController.class);
    
    private static final RoleTemplate[] ADMIN_ROLE_TEMPLATES = { RoleTemplate.ADMIN_USER , RoleTemplate.COMMON_STORAGE_USER};
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private RoleService roleService;
    
    @Autowired
    private ResourceService resourceService;
    
    @Autowired
    private SupplierService supplierService;
    
    @Autowired
    private OrganizationService organizationService;

    /**
     * list all admin_users
     * 
     * @param page
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @MenuSetting("submenu-admin-user-management")
    public ModelAndView list(Page page){
        
        ModelAndView modelAndView = new ModelAndView("authority/user/admin/admin-user-list");
        
        int totals = userService.count(ADMIN_ROLE_TEMPLATES);
        if(totals > 0){
            
            List<User> users = userService.list(ADMIN_ROLE_TEMPLATES, page.with(totals));
            
            modelAndView.addObject("users", users);
            modelAndView.addObject("page", page);
        }
        
        return modelAndView;
        
    }
    
    /**
     * display create panel
     * 
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    @MenuSetting("submenu-admin-user-management")
    public ModelAndView create(){
        
        ModelAndView modelAndView = new ModelAndView("authority/user/admin/admin-user-create");

        List<RoleTemplate> roleTemplates = Arrays.asList(RoleTemplate.ADMIN_USER, RoleTemplate.COMMON_STORAGE_USER);

        // find roles according to the role_template
        List<Role> roles = roleService.list(roleTemplates);
        modelAndView.addObject("roles", roles);
        
        return modelAndView;
        
    }
    
    /**
     * check if already has the user login name
     * 
     * @param loginName
     * @return
     */
    @RequestMapping(value = "/exist-login-name", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult exsitLoginName(@RequestParam(name = "loginName") String loginName){
        
        HttpResult httpResult = new HttpResult();
        
        boolean existLoginName = userService.existLoginName(loginName);
        
        httpResult.success()
                  .data("existLoginName", existLoginName);
        
        return httpResult;
    }
    
    /**
     * on create
     * 
     * @param operator
     * @param user
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @MenuSetting("submenu-admin-user-management")
    public @ResponseBody HttpResult onCreate(@Secure(property = "id") Long operator, User user){
        
        HttpResult httpResult = new HttpResult();
        
        try {

            // list all organizations
            List<Organization> organizations = organizationService.listSystemOrganization();
            
        	userService.createAdminUser(user, organizations, operator);
            
            httpResult.success().message("创建总部用户成功！");
        	
		} catch (Exception e) {
			httpResult.fail("500").message("创建总部用户失败! " + e.getMessage());
			logger.error("#onCreate() - create admin user fail, exception is [{}]", e);
		}
        
        return httpResult;
        
    }
    
    
    /**
     * display edit panel
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/edit", method = RequestMethod.GET)
    public ModelAndView edit(@PathVariable("id") Long id){
        ModelAndView modelAndView = new ModelAndView("authority/user/admin/admin-user-edit");
        
        User user = userService.load(User.class, id);
        
        modelAndView.addObject("user", user);
        return modelAndView;
    }
    
    /**
     * on edit
     * 
     * @param user
     * @param operator
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onEdit(@Preloading("userId") User user,
                                           @Secure(property = "id") Long operator) {
        
        HttpResult httpResult = new HttpResult();
        
        userService.editAdminOrBranch(user, operator);
        
        httpResult.success().message("修改用户成功！");
        
        return httpResult;
        
    }
    
    /**
     * display delete panel
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
    public ModelAndView delete(@PathVariable("id") Long id){
        
        ModelAndView modelAndView = new ModelAndView("authority/user/admin/admin-user-delete");
        
        modelAndView.addObject("id", id);
        
        return modelAndView;
        
    }
    
    /**
     * on delete
     * 
     * @param user
     * @param operator
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onDelete(@Preloading("userId") User user,
                                             @Secure(property = "id") Long operator) {
        
        HttpResult httpResult = new HttpResult();
        
        userService.deleteAdminOrBranch(user, operator);
        
        httpResult.success().message("删除用户成功！");
        
        return httpResult;
    }
    
    /**
     * display reset password panel
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/reset-password", method = RequestMethod.GET)
    public ModelAndView resetPassword(@PathVariable("id") Long id){
        ModelAndView modelAndView = new ModelAndView("authority/user/admin/admin-user-reset-password");
        
        modelAndView.addObject("id", id);
        return modelAndView;
    }
    
    /**
     * on reset password
     * 
     * @param user
     * @param password
     * @param operator
     * @return
     */
    @RequestMapping(value = "/{id}/reset-password", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onResetPassword(@Preloading("userId") User user,
                                                    @RequestParam("password") String password,
                                                    @Secure(property = "id") Long operator){
        
        HttpResult httpResult = new HttpResult();
        
        userService.resetPassword(user, password, operator);
        
        httpResult.success()
                  .message("重置密码成功！");
        
        return httpResult;
    }
    
    /**
     * view
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @MenuSetting("submenu-admin-user-management")
    public ModelAndView view(@PathVariable("id") Long id){
        
        ModelAndView modelAndView = new ModelAndView("authority/user/admin/admin-user-view");
        
        User user = userService.load(User.class, id);
        
        modelAndView.addObject("user", user);
        return modelAndView;
    }
    
    /**
     * view resource（菜单权限）
     * 
     * @param id
     * @param page
     * @return
     */
    @RequestMapping(value = "/{id}/resources", method = RequestMethod.GET)
    @MenuSetting("submenu-admin-user-management")
    public ModelAndView viewResource(@PathVariable("id") Long id, Page page){
        
        ModelAndView modelAndView = new ModelAndView("authority/user/admin/admin-user-resource-view");
        
        // 1. load user by id
        User user = userService.load(User.class, id);
        
        // 2. count resource by user
        int totals = resourceService.count(user);
        
        if(totals > 0){
            
            // 3. list resources by user
            List<Resource> resources = resourceService.list(user, page.with(totals));
            
            modelAndView.addObject("resources", resources);
            modelAndView.addObject("page", page);
        }
        
        modelAndView.addObject("user", user);
        modelAndView.addObject("totals", totals);
        
        return modelAndView;
    }
    
    /**
     * view organizations（运输供应商权限）
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/organizations", method = RequestMethod.GET)
    @MenuSetting("submenu-admin-user-management")
    public ModelAndView viewOrganization(@PathVariable("id") Long id){
        
        ModelAndView modelAndView = new ModelAndView("authority/user/admin/admin-user-organization-view");
        
        // 1. load user by id
        User user = userService.load(User.class, id);
        
        // 2. list all organizations
        List<Organization> organizations = organizationService.listSystemOrganization();
        
        // 3. list organization ids of the user
        List<Long> userOrganizations = organizationService.listUserOrganization(user);
        
        modelAndView.addObject("user", user);
        modelAndView.addObject("organizations", organizations);
        modelAndView.addObject("userOrganizations", userOrganizations);
        
        return modelAndView;
    }
    
    /**
     * on edit organization
     * 
     * @param id
     * @param organizations
     * @param operator
     * @return
     */
    @RequestMapping(value = "/{id}/organizations", method = RequestMethod.PATCH)
    @MenuSetting("submenu-admin-user-management")
    public ModelAndView onOrganization(@PathVariable("id") Long id, 
                                       @RequestParam(value = "organizations") List<Long> organizations,
                                       @Secure(property = "id") Long operator){
        
        ModelAndView modelAndView = new ModelAndView("redirect:/admin-users");
        
        // load user by id
        User user = userService.load(User.class, id);
        
        // edit user_supplier_relation
        userService.editOrganization(user, organizations, operator);
        
        return modelAndView;
        
    }
    
    /**
     * view suppliers（供应商管辖权限）
     * 
     * @param id
     * @param page
     * @return
     */
    @RequestMapping(value = "/{id}/suppliers", method = RequestMethod.GET)
    @MenuSetting("submenu-admin-user-management")
    public ModelAndView viewSupplier(@PathVariable("id") Long id, Page page){
        
        ModelAndView modelAndView = new ModelAndView("authority/user/admin/admin-user-supplier-view");
        
        // 1. load user by id
        User user = userService.load(User.class, id);
        
        // 2. count suppliers by user
        int totals = supplierService.count(Supplier.class);
        
        if(totals > 0){
            
            // 3. list suppliers by user and page
            List<Supplier> suppliers = supplierService.listByPage(Supplier.class, page.with(totals));
            
            modelAndView.addObject("suppliers", suppliers);
            modelAndView.addObject("page", page);
        }
        
        modelAndView.addObject("totals", totals);
        modelAndView.addObject("user", user);
        
        return modelAndView;
    }
    
    /**
     * 同步到VAM
     * @return
     */
    @RequestMapping(value = "/{id}/sync-vam", method = RequestMethod.GET)
    @MenuSetting("submenu-admin-user-management")
    public ModelAndView syncVam(@PathVariable("id") Long userId) {
    	
    	ModelAndView modelAndView = new ModelAndView("authority/user/admin/admin-user-sync-vam");
    	
    	User user = userService.load(User.class, userId);
    	
    	modelAndView.addObject("user", user);
    	
    	return modelAndView;
    }
    
    @RequestMapping(value = "/{id}/sync-vam", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @MenuSetting("submenu-admin-user-management")
    public @ResponseBody HttpResult onSyncVam(@Preloading("userId") User user, @Secure(property = "id") Long operator) {
    	
    	HttpResult httpResult = new HttpResult();
        try {
			userService.editAdminOrBranch(user, operator);
			
            httpResult.success().message("同步至VAM成功！");

		} catch (Exception e) {
			
			httpResult.fail("500").message("同步至VAM失败! " + e.getMessage());
			
			logger.error("#onSysncVam() - sysnc user information to vam fail, exception is [{}]", e);
		}
        return httpResult;
    }
    
    
    
}
